package com.zhj.bz.datastructure.stack;

import java.time.chrono.IsoChronology;
import java.util.Scanner;

/**
 * @author zhj
 */
public class LinkedStackDemo {
    public static void main(String[] args) {
        LinkedStack linkedStack = new LinkedStack();
        String key = "";
        boolean loop = true;
        Scanner scanner = new Scanner(System.in);

        while (loop) {
            System.out.println("show:展示栈");
            System.out.println("exit:退出");
            System.out.println("push:入栈");
            System.out.println("pop:出栈");
            System.out.println("请输入你的选择");
            key = scanner.next();
            switch (key) {
                case "show":
                    linkedStack.show();
                    break;
                case "exit":
                    System.out.println("程序结束");
                    loop = false;
                    break;
                case "push":
                    System.out.println("请输入一个数字：");
                    int num = scanner.nextInt();
                    linkedStack.push(num);
                    break;
                case "pop":
                    try {
                        System.out.println("出栈的数据是" + linkedStack.pop());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    System.out.println("输入非法指令");
                    break;
            }
        }
    }
}
class LinkedStack{
    private Node head = new Node();

    public boolean isEntry() {
        return head.getNext() == null;
    }

    public void push(int n) {
        Node node = new Node(n);
        Node next = head;
        while (next.getNext() != null) {
            next = next.getNext();
        }
        next.setNext(node);
    }

    public int pop() {
        if (isEntry()) {
            throw new RuntimeException("栈空");
        }
        Node next = head;
        while (next.getNext() != null) {
            if (next.getNext().getNext() == null) {
                break;
            }
            next = next.getNext();
        }
        int value = next.getNext().getValue();
        next.setNext(null);
        return value;
    }

    // TODO 未实现逆向输出
    public void show() {
        Node next = head;
        while (next.getNext() != null) {
            next = next.getNext();
            System.out.print(next.getValue() + "\t");
        }
        System.out.println();
    }
}
class Node{
    private int value;
    private Node next;

    public Node(int value) {
        this.value = value;
    }

    public Node() {
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }
}
